package com.itany.boot.controller;

import com.github.pagehelper.PageInfo;
import com.itany.boot.constant.ResponseCodeConstant;
import com.itany.boot.entity.GoldPoints;
import com.itany.boot.entity.User;
import com.itany.boot.exception.RequestParameterErrorException;
import com.itany.boot.service.GoldPointsService;
import com.itany.boot.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * @author 黄衡熙
 * @version 1.0
 */
//是 @Controller + @ResponseBody 的组合注解。
@RestController
@RequestMapping("/goldPoints")
public class GoldPointsController {

    @Autowired
    private GoldPointsService goldPointsService;
    @RequestMapping("/findPage")
    public ModelAndView findAll(String pageNo, String pageSize, HttpSession session) {
        ModelAndView mav = new ModelAndView();
        try {
//            User sessionUser = (User) session.getAttribute("user");
//            if (sessionUser == null) {
//                // 处理未登录情况
//                mav.setViewName("redirect:/showFront");
//                return mav;
//            }
//            String UserId = String.valueOf(sessionUser.getId());
            String UserId="2";
            User user = goldPointsService.showNumber(UserId);
            session.setAttribute("user", user);

            PageInfo<GoldPoints> goldPointsPage = goldPointsService.findPage(UserId, pageNo, pageSize);
            mav.addObject("goldPointsPage", goldPointsPage);
            mav.setViewName("front_record");
        } catch (RequestParameterErrorException e) {
            throw new RuntimeException(e);
        }
        return mav;
    }

    @RequestMapping("/buyGold")
    public ResponseResult buyGold(String UserId, String point,HttpSession session) {
        ResponseResult result = new ResponseResult();
        try {
            goldPointsService.buyGold(UserId,point);
            User user = goldPointsService.showNumber(UserId);
            session.setAttribute("user", user);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        }catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }


}
